package chapter11;

import org.junit.Test;

import java.util.*;

/**
 * @author : DuJiabao
 * @Date : 2021/2/19 17:15
 * @Project : thinking_in_java
 * @File : null.java
 * @Desc :
 */
public class IteratorTest {
  public static void main(String[] args) {
    List<Integer> list = new ArrayList<Integer>();
    Collections.addAll(list, 1, 2, 3, 4, 5, 6, 7, 8, 9);
    Iterator<Integer> iterator = list.iterator(); // 获取该容器的迭代器
    // 遍历
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }

    iterator = list.iterator();
    for (int i = 0; i < 3; i++) {
      System.out.println(iterator.next());
      iterator.remove();
    }
    System.out.println(list); // [4, 5, 6, 7, 8, 9]
  }

  @Test
  public void test() {
    List<Integer> list = new ArrayList<>();
    Collections.addAll(list, 1, 2, 3, 5, 6, 6);
    display(list.iterator());

    List<Double> doubles = new ArrayList<>();
    Collections.addAll(doubles, 1., 2., 3., 5., 6., 6.);
    display(doubles.iterator());

  }

  /**
   * 显示所有元素
   *
   * @param iterator 任意类型的迭代器
   */
  public void display(Iterator<?> iterator) {
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
}
